//
//  WPTreamentAddNewVisitVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/12/5.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPTreamentAddNewVisitVC.h"
#import "WPMRModel.h"
#import "WPMinePlaceholderTextView.h"
#import "WPTreamentProgressListModel.h"
#import "TZAssetModel.h"

@interface WPTreamentAddNewVisitVC ()

@property(nonatomic,strong)WPMRModel *addNewVisitModel;
@property(nonatomic,assign)BOOL isSaved;

@end

@implementation WPTreamentAddNewVisitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

-(void)setModel:(WPMRModel *)model
{
    _addNewVisitModel = model;
}

-(void)saveBtnDidClick:(UIButton *)btn
{
    if (!self.textView.attributedText.length)
    {
        [self showInfoStatus:@"内容不能为空"];
        return ;
    }
    
    //保存治疗说明
    NSString *url = @"record/editProcessDescp.do";
    
    // 1. 发送带有图片标志的纯文本到服务器
    NSString *textString = [self textStringWithSymbol:@"[图片]" attributeString:self.textView.attributedText];
    
    [self showWithStatus:@"正在保存"];
    
    
    //去掉多余的图片前的换行符
    textString = [self deleteNewlineWith:textString];
        
    //治疗过程的复诊的保存
    WPEditeModel *editeModel = [WPEditeModel new];
    editeModel.recordId = self.addNewVisitModel.id;
    editeModel.rank = self.rank;
    if (![self.timeBtn.titleLabel.text isEqualToString:@"请输入治疗时间"])
    {
        editeModel.writeTime = self.timeBtn.titleLabel.text;
    }
    else
    {
        editeModel.writeTime = @"";
    }
    editeModel.descp = textString;
    
    NSString *JSONStr = [editeModel yy_modelToJSONString];
    NSDictionary *dict = @{@"json":JSONStr};
    if (self.photos.count)
    {
        for (NSNumber *index in self.imageNameArr)
        {
            int i = index.intValue-1;
            if (i >= 0)
            {
                UIImage *image = self.photos[i];
                NSString *totalPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lu.jpg",(unsigned long)i+1]];
                
                NSData *data = UIImageJPEGRepresentation(image, 0.6);
                [data writeToFile:totalPath atomically:NO];
                
                NSURL *imageURL = [NSURL fileURLWithPath:totalPath];
                
                [self.pathArr addObject:imageURL];
            }
        }
    }
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSURL *imageURL in self.pathArr)
        {
            [formData appendPartWithFileURL:imageURL name:@"file" error:nil];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        if([responseObject[@"result"] isEqualToString:@"success"])
        {
            
//            NSDictionary *dict = responseObject[@"detail"];
//            
//            WPTreamentProgressListModel *visiteModel = nil;
//            if (self.model.processDescp_list.count > (self.rank-2))
//            {
//                //不是第一次
//                visiteModel = self.model.processDescp_list[self.rank-2];
//            }
//            else
//            {
//                visiteModel = [WPTreamentProgressListModel new];
//                visiteModel.descp = dict[@"descp"];
//                visiteModel.descp_list = dict[@"descp_list"];
//                visiteModel.writeTime = dict[@"writeTime"];
//                visiteModel.rank = [dict[@"rank"] intValue];
//                visiteModel.recordId = [dict[@"recordId"] integerValue];
//                visiteModel.id = [dict[@"id"] intValue];
  
//                NSMutableArray *models = [NSMutableArray arrayWithArray:self.addNewVisitModel.processDescp_list];
//                [models addObject:visiteModel];
//                self.addNewVisitModel.processDescp_list = models;
//            }
            
            WPTreamentProgressListModel *model = [WPTreamentProgressListModel yy_modelWithDictionary:responseObject[@"detail"]];
            
            if (self.isSaved)
            {
                
                NSInteger index = self.addNewVisitModel.processDescp_list.count;
                [(NSMutableArray *)self.addNewVisitModel.processDescp_list replaceObjectAtIndex:index-1 withObject:model];
            }
            else
            {
                NSMutableArray *models = [NSMutableArray arrayWithArray:self.addNewVisitModel.processDescp_list];
                [models addObject:model];
                self.addNewVisitModel.processDescp_list = models;
            }
            self.isSaved = YES;
            
            [self showSuccessInfoWithStatus:@"保存成功"];
            
            //刷新
            if (self.reloadBlock)
            {
                self.reloadBlock();
            }
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                [self illegalLoginWithSuccessBlock:^{
                    
                    //点击确定后的回调
                    
                }];
            }
            else
            {
                [self showErrorInfoWithStatus:responseObject[@"detail"]];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)uploadVideoOrAudioToServeWith:(TZAssetModel *)model index:(NSInteger)index
{
    self.uploadingIndex = index;
    
    //上传服务器
    NSString *url = @"record/uploadMultfile.do";
    
    NSDictionary *dict = @{@"recordId":@(self.addNewVisitModel.id),@"rank":@(self.rank)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:model.urlPath name:@"file" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        CGFloat progress = ((CGFloat)uploadProgress.completedUnitCount)/uploadProgress.totalUnitCount;
        WPVideoAndVoiceCell *cell = (WPVideoAndVoiceCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            cell.progressView.progress = progress;
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = responseObject[@"detail"];
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            model.isUploaded = YES;
            [self showResultOfVideoOrAudioUploadWith:YES];
            
            NSMutableArray *arr = [NSMutableArray array];
            
            NSArray *multFile_list = dict[@"multFile_list"];
            for (NSDictionary *videoOrAudioDict in multFile_list)
            {
                WPVideoOrAudioModel *model = [WPVideoOrAudioModel yy_modelWithDictionary:videoOrAudioDict];
                [arr addObject:model];
            }
            WPTreamentProgressListModel *visiteModel = nil;
            if (self.model.processDescp_list.count > (self.rank-2))
            {
                //不是第一次
                visiteModel = self.model.processDescp_list[self.rank-2];
            }
            else
            {
                //第一次
                visiteModel = [WPTreamentProgressListModel new];
                
                NSMutableArray *processDescp_list = [NSMutableArray arrayWithArray:self.model.processDescp_list];
                
                [processDescp_list addObject:visiteModel];
                self.model.processDescp_list = processDescp_list;
            }
            
            visiteModel.multFile_list = arr;
            
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                [self illegalLoginWithSuccessBlock:^{
                    
                    //点击确定后的回调
                }];
            }
            else
            {
                [self showResultOfVideoOrAudioUploadWith:NO];
            }
            
        }
        self.uploadingIndex = -1;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        WPVideoAndVoiceCell *cell = (WPVideoAndVoiceCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            cell.failedImageView.hidden = NO;
        });
        [self showErrorInfoWithStatus:@"网络错误"];
        self.uploadingIndex = -1;
    }];
}

@end
